package com.example.demo.modules.oss.controller;

import cn.hutool.core.util.StrUtil;
import com.example.demo.common.util.OSSUtil;
import com.example.demo.common.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@RestController
@RequestMapping("/api/upload")
public class FileController {
    @Autowired
    OSSUtil ossUtil;

    @GetMapping("/")
    public R func() {
        return R.ok("这是之定义字段");
    }

    public Boolean isImage(String fileName) {
        String extension = "";
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i + 1).toLowerCase();
        }
        if ("jpg".equals(extension)) {
            return true;
        }
        if ("png".equals(extension)) {
            return true;
        }
        if ("webp".equals(extension)) {
            return true;
        }
       /* if ("gif".equals(extension)) {
            return true;
        }*/
        if ("svg".equals(extension)) {
            return true;
        }
        return false;
    }

    public Boolean isVideo(String fileName) {
        String extension = "";
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i + 1).toLowerCase();
        }
        if ("mp4".equals(extension)) {
            return true;
        }
        return false;
    }

    public String getFileSuffix(String fileName) {
        String extension = "";
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i + 1).toLowerCase();
        }
        return extension;
    }

    @PostMapping("/image")
    public R upLoadImage(@RequestParam("file") MultipartFile file,
                         @RequestParam(value = "fileName", required = false) String fileName) throws IOException {
        String _fileName = file.getOriginalFilename();
        if (!isImage(_fileName)) {
            return R.error("请上传图片【jpg png webp svg】资源");
        }
        //清空文件尾缀
        int i = _fileName.lastIndexOf(".");
        String fileNameWithNotSuffix = "";
        if (i > 0) {
            fileNameWithNotSuffix = StrUtil.sub(_fileName, 0, i);
        }


        if (Double.parseDouble(String.valueOf(file.getSize())) / 1024 / 1024 > 1) {
            return R.error(StrUtil.format("文件大小：{}M，文件不能大于1M", Double.parseDouble(String.valueOf(file.getSize())) / 1024 / 1024));
        }

        String ___fileName = _fileName;
        if (null != fileName && !("".equals(fileName))) {
            ___fileName = fileName;
        }
        String upload = ossUtil.upload(___fileName, file.getInputStream());
        return R.ok().put("msg", upload);
    }
}
